import React from 'react';
import {Spin, Card, Button, Row, Col, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS} from '../constants';
import {addApplyReport, updateApplyReport, getDetail} from './api';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import TechnologyActivitySelectPanel from './TechnologyActivitySelectPanel';
import WrappedDatePicker from '../common/WrappedDatePicker';
import {injectIntl, formatMessage} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import {formatPercent} from '../utils';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
import FileUpload from './FileUpload';
const EMPTY_ARRAY = [];
const FormItem = Form.Item;

class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showTechnologyActivitySelectPanel: false,
        data: {},
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data,
                        });
                    else
                        this.setState({loading: false});
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const isValid = newOrUpdateOrderValidator(data);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            technologyActivityId: data.technologyActivityId,
            telephone: data.telephone,
            email: data.email,
            completionRate: data.completionRate,
            delayReason: data.delayReason,
            deadlineTime: data.deadlineTime,
            rowVersion: data.rowVersion,
            attachments: data.attachments === undefined ? '' : data.attachments.map(v => ({
                fileId: v.fileId,
                fileName: v.fileName
            }))
        };
        this.setState({loading: true});
        if(data.id)
            updateApplyReport(this.props.id, condition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        else
            addApplyReport(condition).then(res => {
                if(res.ok)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    onClickSearchTechnologyActivityBtn = () => {
        this.setState({
            showTechnologyActivitySelectPanel: true
        });
    }
    onCloseTechnologyActivitySelectPanel = () => {
        this.setState({showTechnologyActivitySelectPanel: false});
    }
    onSelectTechnologyActivity = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                technologyActivityId: records.id,
                technologyActivityCode: records.code,
                technologyActivityName: records.serviceName,
                completionRate: records.completionRate,
            }),
            hasOperat: true,
            showTechnologyActivitySelectPanel: false
        });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    render() {
        const {data, isValidate, loading} = this.state;
        const {brands = []} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '技术升级延期申请信息'
                    })}>
                        <Form>
                            <Row>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.data.technologyActivityId',
                                        defaultMessage: '技术升级'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.technologyActivityId ? 'error' : null} required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.technologyActivityCode === undefined
                                                ? ''
                                                : `(${data.technologyActivityCode})${data.technologyActivityName}`}
                                            onClickSearchBtn={() => this.onClickSearchTechnologyActivityBtn()} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.telephone',
                                        defaultMessage: '电话'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.telephone ? 'error' : null} required>
                                        <TextInput
                                            name="telephone"
                                            value={data.telephone}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.email',
                                        defaultMessage: '电子邮件'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.email ? 'error' : null} required>
                                        <TextInput
                                            name="email"
                                            value={data.email}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.completionRate',
                                        defaultMessage: '完成率'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.completionRate ? 'error' : null} required>
                                        {formatPercent(data.completionRate)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.delayReason',
                                        defaultMessage: '活动延期原因'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.delayReason ? 'error' : null} required>
                                        <TextInput
                                            name="delayReason"
                                            value={data.delayReason}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'addPanel.operation.deadlineTime',
                                            defaultMessage: '活动推迟截止时间'
                                        })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.deadlineTime ? 'error' : null} required>
                                        <WrappedDatePicker
                                            name="deadlineTime"
                                            value={data.deadlineTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showTechnologyActivitySelectPanel &&
                    <TechnologyActivitySelectPanel
                        selectKey={data.productCategoryId}
                        onCancel={this.onCloseTechnologyActivitySelectPanel}
                        onSelect={this.onSelectTechnologyActivity} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
